package core;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import util.NBGStrParser;

import NET.sourceforge.BplusJ.BplusJ.BplusTree;

public class RawDataIndex {
	String treeFile = "D:/research/parinet/meta/indexidtreetest";
	String blockFile = "D:/research/parinet/meta/indexidblocktest";
	String sampleKey = "1000000";
	private BplusTree btp;

	/**
	 * @param args
	 * @throws Exception
	 */
	public RawDataIndex(String treeFile, String blockFile){
		this.treeFile = treeFile;
		this.blockFile = blockFile;
	}
	
	public void indexNBGFileById(String fileName) {
		System.out.println("Indexing NBG file by id...");
		BufferedReader in;

		try {
			btp = BplusTree.Initialize(treeFile, blockFile, sampleKey.length());
			in = new BufferedReader(new FileReader(fileName));
			String str;
			int count = 0;
			while ((str = in.readLine()) != null) {
				if (count % 10000 == 0) {
					System.out.println("Indexing progress: " + count);
				}
				count++;
				NBGStrParser rawDataParser = new NBGStrParser(str);
				int lineOid = rawDataParser.getOid();
				if (btp.ContainsKey(lineOid + "")) {
					String val = btp.get(lineOid + "") + ";" + str;
					btp.Set(lineOid + "", val);
				} else {
					btp.Set(lineOid + "", str);
				}
			}
			in.close();
			btp.Commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public BplusTree open() throws Exception {
		return BplusTree.ReadOnly(treeFile, blockFile);
	}

//	// public static void main(String[] args) throws Exception{
//	// RawDataIndex in = new RawDataIndex();
//	// BplusTree tree = BplusTree.ReadOnly(in.treeFile, in.blockFile);
//	// int[] ids = {1, 2, 3};
//	// for (int id : ids){
//	// System.out.println(tree.ContainsKey(id+""));
//	// }
//	// }
//	public static void main(String[] args) throws Exception {
//		RawDataIndex in = new RawDataIndex();
//		in.indexNBGFileById("d:/research/parinet/dataset/test.txt");
//		BplusTree tree = BplusTree.ReadOnly(in.treeFile, in.blockFile);
//		int[] ids = { 1, 2, 3 };
//		for (int id : ids) {
//			System.out.println(tree.ContainsKey(id + ""));
//		}
//	}
}
